<?php
include 'core.php';

class Authorization {
	
	private  $username;
	private  $password;
	
	/**
	 * constructor
	 */
	function Authorization() {
	}
	
	/**
	 * @param string $username სისტემის მომხმარებელი
	 */
	function set_username($username) {
		$this->username = $username;
	}
	
	/**
	 * @param string $password მომხმარებლის პაროლი
	 */
	function set_password($password) {
		$this->password = md5($password);
	}
	
	function login (){
		
		if ($this->username != '' && $this->password != '' ) {
			
				$result = mysql_query("	
									  SELECT 	`id`
									  FROM 	`users`
									  WHERE	`password` = '$this->password' AND username = '$this->username' AND `actived` = 1
									  ");
				
				if (mysql_num_rows($result) == 1) {
					
					$now =  date("Y-m-d H:i:s");
					
					$lifetime=86400;
					session_cache_expire($lifetime);
					$cache_expire = session_cache_expire();
					
					session_start();
					
					$session_id_old = session_id();
					session_regenerate_id();
					$session_id_new = session_id();
					
					$row = mysql_fetch_assoc($result);
					date_default_timezone_set('Asia/Tbilisi');
					setcookie('USERID', $row['id'], time()+$lifetime);
					setcookie('SESSID', $session_id_new, time()+$lifetime);
					
					mysql_query("
								UPDATE 	`users`
								SET		`session_id` = '$session_id_new',
										`login_date` = '$now'
								WHERE	`id` = $row[id]
								");
					
					return true;
				}else {
					return false;
				}
		}else {
			return false;
		}
	}
	
	function logout(){
		session_start();
		setcookie('USERID', '');
		setcookie('SESSID', '');
		session_destroy();
		session_unset();	
		return true;
	}
	
	function __destruct() {
	}
}

?>